<?php

$image = $_GET["image"];
$w = $_GET["w"];
$h = $_GET["h"];
$bg = $_GET["bg"]; $bg = isset($bg) ? $bg : "black";

if($image){
	Image::img_show($image, $w, $h, $bg);	
}

class Image{

	public static function img_show($path, $w=null, $h=null, $bg=null){
		$img = self::img_create($path);
		if($w || $h){
			self::img_resize($img, $w, $h, $bg);
		}
		self::img_throw($img, substr($path, strrpos($path, "/"), strrpos($path, ".")));
	}

	public static function img_create($path){
		return new Imagick($path);
	}

	public static function img_throw($img, $name){
		$ext = strtolower(substr($name, strrpos($name, ".")+1));
		$img->setImageFormat($ext);
		header("Content-Type: image/$ext");
		header("Content-Disposition: inline; filename=$name");
		echo $img;
	}

	public static function img_resize(&$img, $w=null, $h=null, $bg=null){
		$bg = isset($bg) ? $bg : "black";
		$w1 = $img->getImageWidth();
		$h1 = $img->getImageHeight();
		$img->scaleImage($w>0 ? $w : $w1, $h>0 ? $h : $h1, true);
		$width = $img->getImageWidth();
		$height = $img->getImageHeight();
		if($w>0 && $h>0) {
			$img2 = new Imagick();
			$img2->newImage($w, $h, new ImagickPixel($bg));
			$l = ($w-$width)/2; 
			$t = ($h-$height)/2;
			$img2->compositeImage($img, Imagick::COMPOSITE_COPY, $l, $t);
			$img = $img2;
		}
	}
}